package com.x.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;

import java.sql.Connection;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @title: DynamicDataSource
 * @Author X
 * @Date: 2021/1/4 14:58
 * @Version 1.0
 */
public class DynamicRoutingDataSource extends AbstractRoutingDataSource {
    private static final Logger logger = LoggerFactory.getLogger(DynamicRoutingDataSource.class);

    private Map<Object, Object> targetDataSources;

    public DynamicRoutingDataSource(Map<Object, Object> targetDataSources)
    {
        if(targetDataSources.isEmpty()) {
            this.targetDataSources = new ConcurrentHashMap<>();
        }
        this.targetDataSources = targetDataSources;
        flushDataSource();
    }

    @Override
    protected Object determineCurrentLookupKey() {
        String dataSource = DynamicDataSourceContextHolder.getDataSource();
        DruidDataSource druidDataSource = (DruidDataSource) targetDataSources.get(dataSource);
        logger.info("dataSource: {}, url: {}", dataSource, druidDataSource.getUrl());
        return dataSource;
    }

    public boolean addNewDataSource(String dataSourceId, String driverClassName, String url, String username, String password) {
        DynamicCustomerDataSource dynamicCustomerDataSource = new DynamicCustomerDataSource();
        DruidDataSource createDefaultDruidDataSource = dynamicCustomerDataSource.createDefaultDruidDataSource();
        createDefaultDruidDataSource.setDriverClassName(driverClassName);
        createDefaultDruidDataSource.setUrl(url);
        createDefaultDruidDataSource.setUsername(username);
        createDefaultDruidDataSource.setPassword(password);
        try (Connection WCCdsconn = createDefaultDruidDataSource.getConnection()) {
            createDefaultDruidDataSource.init();
            targetDataSources.put(dataSourceId, createDefaultDruidDataSource);
            flushDataSource();
            logger.info("dataSourceId: {}, url: {}, 初始化成功", dataSourceId, url);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            logger.info("dataSourceId: {}, url: {}, 初始化失败！！！", dataSourceId, url);
        }
        return false;
    }

    public void removeDataSource(String dataSourceId) {
        this.targetDataSources.remove(dataSourceId);
        flushDataSource();
    }


    private void flushDataSource() {
        super.setTargetDataSources(this.targetDataSources);
        super.afterPropertiesSet();
    }
}
